package com.nowcoder.community.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * @author 韩
 * @version 1.0
 * 敏感词过滤器
 */
@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    //替换字符
    private static final String REPLACEWORDS = "***";

    //根节点
    private TrieNode root = new TrieNode();

    @PostConstruct//服务器初始化将SensitiveFilter放入容器时，构造器之后执行初始化方法，完成对前缀树的初始化
    public void init() {
        try (
                //类路径下获取敏感词的输入流
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                //转换成缓冲字符流
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String keyword;
            while ((keyword = reader.readLine()) != null) {
                this.addKeyword(keyword);
            }
        } catch (IOException e) {
            logger.error("读取敏感词文件异常：" + e.getMessage());
        }
    }

    //添加敏感词
    private void addKeyword(String keyword) {
        TrieNode tempNode = root;
        int len = keyword.length();
        for (int i = 0; i < len; i++) {
            char c = keyword.charAt(i);
            //获取下一个节点，不存在就创建，并添加子节点
            TrieNode subNode = tempNode.getSubNode(c);
            if (subNode == null) {
                subNode = new TrieNode();
                tempNode.setSubNode(subNode, c);
            }
            //当前节点赋为下一个节点
            tempNode = subNode;
        }
        //设置结束字符标志
        tempNode.setKeyWordEnd(true);
    }

    //过滤敏感词
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        TrieNode tempNode = root;
        int n = text.length();
        int start = 0;//开头指针
        int cur = 0;//当前指针
        StringBuilder sb = new StringBuilder();
        while (start < n) {
            //如果当前指针没有到达结尾，继续过滤
            if (cur < n) {
                char c = text.charAt(cur);

                //跳过符号
                if (isSymbol(c)) {
                    //当前节点在根节点，直接跳过该符号
                    if (tempNode == root) {
                        sb.append(c);
                        start++;
                    }
                    //无论符号在开头还是中间，当前指针跳过
                    cur++;
                    continue;
                }

                //检查当前字符是否是下级节点
                TrieNode subNode = tempNode.getSubNode(c);
                if (subNode == null) {
                    //子节点当前字符为null，表示start字符开头的不是敏感词
                    sb.append(c);
                    cur = ++start;
                    //指向根节点
                    tempNode = root;
                } else if (subNode.getKeyWordEnd()) {
                    //说明当前start到cur之间的字符为敏感词
                    sb.append(REPLACEWORDS);
                    start = ++cur;
                    tempNode = root;
                } else {
                    //有子节点但是不是结束节点，继续往后检测
                    cur++;
                    tempNode = subNode;
                }
            } else {//当前指针到达结尾,当前指针到start下一个位置重新过滤
                sb.append(text.charAt(start));
                cur = ++start;
                tempNode = root;//重新到前缀树根节点开始
            }
        }
        return sb.toString();
    }

    private boolean isSymbol(Character c) {
        //判断是否是特殊字符，符号之类的;    0x2E80~0x9FFF 是东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    private class TrieNode {
        //标注敏感词的最后一个词
        private boolean isKeyWordEnd;
        //key存放下一个字符，value存放子节点
        private HashMap<Character, TrieNode> subNode = new HashMap<>();

        public boolean getKeyWordEnd() {
            return isKeyWordEnd;
        }

        public void setKeyWordEnd(boolean keyWordEnd) {
            isKeyWordEnd = keyWordEnd;
        }

        public TrieNode getSubNode(Character c) {
            return subNode.get(c);
        }

        public void setSubNode(TrieNode node, Character c) {
            subNode.put(c, node);
        }

    }
}
